//
//  PHCaptchaView.m
//  SmallElephant
//
//  Created by Faith on 2024/11/25.
//

#import "PHCaptchaView.h"

@interface PHCaptchaView() <UITextFieldDelegate>

@property (nonatomic, strong) NSMutableArray<UITextField *> *textFields; // 存储输入框

@property (nonatomic, strong) NSString *currentCode; // 当前验证码

@end

@implementation PHCaptchaView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    return self;
}

- (void)layoutSubviews {
    [self setupUI];
}

- (void)setupUI {
    [self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    self.textFields = [NSMutableArray array];
    CGFloat spacing = 10.0; // 间距
    CGFloat fieldWidth = (self.frame.size.width - spacing * 5) / 6; // 输入框宽度
    CGFloat fieldHeight = fieldWidth;
    for (int i = 0; i < 6; i++) {
        UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(i * (fieldWidth + spacing), 0, fieldWidth, fieldHeight)];
        textField.borderStyle = UITextBorderStyleRoundedRect;
        textField.textAlignment = NSTextAlignmentCenter;
        textField.keyboardType = UIKeyboardTypeNumberPad;
        textField.font = [UIFont systemFontOfSize:20];
        textField.delegate = self;
        textField.tag = i;
        [textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
        //[textField addTarget:self action:@selector(dee:) forControlEvents:UIControlEventAllEvents];
        
        [self.textFields addObject:textField];
        [self addSubview:textField];
    }
}

- (void)dee:(id)button {
    NSLog(@"按键： %@",button);
}

#pragma mark - UITextFieldDelegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (string.length > 1) {
        return NO; // 禁止粘贴多字符
    }
    return YES;
}

- (void)textFieldDidChange:(UITextField *)textField {
    NSInteger tag = textField.tag;
    if (textField.text.length > 1) {
        textField.text = [textField.text substringToIndex:1]; // 限制每个格子只能输入1位
    }
    
    if (textField.text.length == 1) {
        if (tag < 5) {
            [self.textFields[tag + 1] becomeFirstResponder]; // 自动跳转到下一个输入框
        } else {
            [textField resignFirstResponder]; // 最后一格完成时收起键盘
            [self checkAndSubmitCode]; // 检查并提交验证码
        }
    } else if (textField.text.length == 0 && tag > 0) {
        [self.textFields[tag - 1] becomeFirstResponder]; // 删除时回退到前一个格子
    }
}


#pragma mark - 检查并提交验证码
- (void)checkAndSubmitCode {
    NSMutableString *code = [NSMutableString string];
    for (UITextField *textField in self.textFields) {
        if (textField.text.length == 0) {
            return; // 如果有未填写的格子，不执行提交
        }
        [code appendString:textField.text];
    }
    
    self.currentCode = [code copy];
    if (self.onCodeEntered) {
        self.onCodeEntered(self.currentCode); // 回调完成的验证码
    }
}

@end
